package com.yc.hwc.web.util;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.HandlerInterceptor;

import com.yc.hwc.bean.User;
import com.yc.hwc.dao.IUserExDao;

@Component
public class PubInterceptor implements HandlerInterceptor {

	@Resource
	private IUserExDao ud;

	@Override
	@Transactional
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 运行跨域
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET");
		response.setHeader("Access-Control-Allow-Headers", "Access-Control");
		response.setHeader("Allow", "GET");
		// 一周免登陆
		if (request.getSession().getAttribute("loginedUser") == null) {
			Cookie[] cs = request.getCookies();
			if (cs != null) {
				for (Cookie c : cs) {
					if ("KYRBOGHFHNK".equals(c.getName())) {
						try {
							User dbuser = ud.getOne(Long.parseLong(c.getValue()));
							dbuser.getInUser();
							request.getSession().setAttribute("loginedUser", dbuser);
							c.setMaxAge(60 * 60 * 24 * 7);
							c.setHttpOnly(true);
							response.addCookie(c);
							return true;
						} catch (Exception e) {
							e.printStackTrace();
							break;
						}
					}
				}
			}
		}
		return true;
	}

}
